package liuliu.throughwaring.ui.activity;

import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.drawable.BitmapDrawable;
import android.net.Uri;
import android.text.Editable;
import android.text.TextWatcher;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AbsListView;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.PopupWindow;
import android.widget.RelativeLayout;
import android.widget.ScrollView;
import android.widget.TextView;

import net.tsz.afinal.annotation.view.CodeNote;

import java.util.List;

import liuliu.custom.control.dialog.LLDialog;
import liuliu.custom.control.toolbar.TToolbar;
import liuliu.custom.method.Utils;
import liuliu.throughwaring.R;
import liuliu.throughwaring.adapter.CommonAdapter;
import liuliu.throughwaring.adapter.ViewHolder;
import liuliu.throughwaring.base.BaseActivity;
import liuliu.throughwaring.model.CompanyModel;
import liuliu.throughwaring.view.Util;

/**
 * 从业人员，租赁人员单位管理
 * Created by Administrator on 2016/4/27.
 */
public class CongyeAndZulinActivity extends BaseActivity {
    public static CongyeAndZulinActivity mInstance;
    @CodeNote(id = R.id.main_ttbar)
    TToolbar main_ttbar;//顶部导航
    @CodeNote(id = R.id.no_data_ll)
    LinearLayout no_data_ll;//无数据
    @CodeNote(id = R.id.congye_lv)
    ListView congye_lv;//显示列表数据
    @CodeNote(id = R.id.unit_search_btn, click = "onClick")
    Button unit_search_btn;//单位查询按钮
    @CodeNote(id = R.id.unit_add_btn, click = "onClick")
    Button unit_add_btn;//单位添加按钮
    @CodeNote(id = R.id.total_sv)
    ScrollView total_sv;
    @CodeNote(id = R.id.total_num_tv)
    TextView total_num_tv;//查询出的单位总数
    private String style = "";
    private CommonAdapter mAdapter;
    private LLDialog llDialog;
    private List<CompanyModel> mCompanys;
    private String companyType = "";
    private PopupWindow bottom_pop;
    private String tiaojian_str = "";

    @Override
    public void initViews() {
        setContentView(R.layout.activity_congye_zulin);
        mInstance = this;
        style = getIntent().getStringExtra("style");//传递过来的参数（1.从业人员。2.租赁人员）
        switch (style) {
            case "congye":
                main_ttbar.setLeftTitle("单位管理");
                unit_search_btn.setText("单位查询");
                unit_add_btn.setText("单位添加");
                companyType = "Company";
                break;
            case "zulin":
                main_ttbar.setLeftTitle("房屋管理");
                unit_search_btn.setText("房屋查询");
                unit_add_btn.setText("房屋添加");
                companyType = "Lease";
                break;
        }
    }

    @Override
    public void initEvents() {
        main_ttbar.setLeftOnClick(new TToolbar.LeftOnClickListener() {
            @Override
            public void leftclick() {
                mInstance.finish();
            }
        });
        initCompanys();
    }

    /**
     * 显示PopWindow
     *
     * @param v 点击的组件
     */
    private void showPopWindow(View v) {
        LayoutInflater layoutInflater = (LayoutInflater) getSystemService(Context.LAYOUT_INFLATER_SERVICE);
        View view = layoutInflater.inflate(R.layout.pop_search_word, null);
        final EditText danwei_et = (EditText) view.findViewById(R.id.danwei_name_et);
        if (tiaojian_str != "") {
            danwei_et.setText(tiaojian_str);
            danwei_et.setSelection(tiaojian_str.length());
        }
        final Button cha = (Button) view.findViewById(R.id.cha_btn);
        switch (style) {
            case "congye":
                danwei_et.setHint("单位名称");
                break;
            case "zulin":
                danwei_et.setHint("房屋名称");
                break;
        }

        danwei_et.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {

            }

            @Override
            public void afterTextChanged(Editable s) {
                if (!danwei_et.getText().toString().isEmpty()) {
                    cha.setText("查询");
                } else {
                    cha.setText("取消");
                }
            }
        });
        cha.setOnClickListener(new View.OnClickListener() {//天气信息被点击进行跳页
            @Override
            public void onClick(View v) {
                if (cha.getText().equals("查询")) {
                    tiaojian_str = danwei_et.getText().toString().trim();
                    main_ttbar.setLeftTitle("条件：" + tiaojian_str);
                } else if (cha.getText().equals("取消")) {
                    tiaojian_str = "";
                    switch (style) {
                        case "congye":
                            main_ttbar.setLeftTitle("单位管理");
                            break;
                        case "zulin":
                            main_ttbar.setLeftTitle("房屋管理");
                            break;
                    }
                }
                bottom_pop.dismiss();
                initCompanys();//加载指定公司信息
            }
        });
        bottom_pop = new PopupWindow(view, LinearLayout.LayoutParams.MATCH_PARENT, LinearLayout.LayoutParams.MATCH_PARENT);
        bottom_pop.setAnimationStyle(R.style.pop_main_bottom_anim_style);
        bottom_pop.setFocusable(true);
        bottom_pop.setOutsideTouchable(true);
        bottom_pop.setBackgroundDrawable(new BitmapDrawable());
        bottom_pop.showAtLocation(v, Gravity.BOTTOM, LinearLayout.LayoutParams.MATCH_PARENT, LinearLayout.LayoutParams.MATCH_PARENT);
        bottom_pop.setOnDismissListener(new PopupWindow.OnDismissListener() {
            @Override
            public void onDismiss() {
                bottom_pop.dismiss();
            }
        });
    }


    /**
     * 加载指定条件下的公司信息
     */
    private void initCompanys() {
        mCompanys = finalDb.findAllByWhere(CompanyModel.class, "CompanyType='" + companyType + "' and CompanyName like '%" + tiaojian_str + "%' order by CompanyCreateTime desc");
        if (mCompanys.size() > 0) {
            switch (style) {
                case "congye":
                    total_num_tv.setText("单位总数：" + mCompanys.size() + "个");
                    break;
                case "zulin":
                    total_num_tv.setText("房屋信息：" + mCompanys.size() + "条");
                    break;
            }
            no_data_ll.setVisibility(View.GONE);
            congye_lv.setVisibility(View.VISIBLE);
            mAdapter = new CommonAdapter<CompanyModel>(mInstance, mCompanys, R.layout.item_congye_zulin) {
                @Override
                public void convert(ViewHolder holder, final CompanyModel model, int position) {
                    holder.setText(R.id.xuhao_tv, (position + 1) + "");
                    String companyName = model.getCompanyName();
                    if (companyName.length() > 14) {
                        companyName = companyName.substring(0, 14) + "...";
                    }
                    holder.setComapnyImageUrl(R.id.touxiang_iv, model.getCompanyOveralImageUrl());
                    holder.setText(R.id.company_name_tv, companyName);
                    holder.setText(R.id.tel_tv, model.getCompanyPhoneNumber());
                    holder.setText(R.id.company_address_tv, model.getCompanyAddress());
                    holder.setOnClickListener(R.id.call_btn, new View.OnClickListener() {
                        @Override
                        public void onClick(View v) {//拨打电话
                            Intent intent = new Intent();
                            intent.setAction(Intent.ACTION_DIAL);
                            intent.setData(Uri.parse("tel:" + model.getCompanyPhoneNumber()));
                            startActivity(intent);
                        }
                    });
                    holder.setOnClickListener(R.id.guanli_btn, new View.OnClickListener() {
                        @Override
                        public void onClick(View v) {//管理按钮,跳转到单位详细信息页面
                            mUtils.IntentPost(CompanyDetailActivity.class, new Utils.putListener() {
                                @Override
                                public void put(Intent intent) {
                                    intent.putExtra("CompanyId", model.getCompanyId());
                                }
                            });
                        }
                    });
                    if (companyType.equals("Lease")) {
                        holder.setVisible(R.id.fangzhu_name_tv, true);
                        holder.setText(R.id.fangzhu_name_tv, model.getCompanyLegalPerson());
                        holder.setVisible(R.id.fangzhu_line_ll, true);
                        holder.setVisible(R.id.tel_iv, false);
                        if (model.getHMenpai() == null) {
                            model.setHMenpai("A座403");
                        }
                        holder.setText(R.id.company_address_tv, model.getCompanyAddress() + model.getHMenpai());
                    }
                }
            };
            congye_lv.setAdapter(mAdapter);
            congye_lv.setOnItemClickListener(new AdapterView.OnItemClickListener() {
                @Override
                public void onItemClick(AdapterView<?> parent, View view, final int position, long id) {
                    mUtils.IntentPost(CompanyDetailActivity.class, new Utils.putListener() {
                        @Override
                        public void put(Intent intent) {//管理按钮,跳转到单位详细信息页面
                            intent.putExtra("CompanyId", mCompanys.get(position).getCompanyId());
                        }
                    });
                }
            });
        } else {
            switch (style) {
                case "congye":
                    total_num_tv.setText("单位总数：0个");
                    break;
                case "zulin":
                    total_num_tv.setText("房屋信息：0条");
                    break;
            }
            no_data_ll.setVisibility(View.VISIBLE);
            congye_lv.setVisibility(View.GONE);
        }
    }


    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.unit_add_btn://单位添加按钮点击事件
                switch (companyType) {
                    case "Company":
                        startActivityForResult(new Intent(this, RegUnitActivity.class), 0);
                        break;
                    case "Lease":
                        startActivityForResult(new Intent(this, RegChuzuwuActivity.class), 0);
                        break;
                }

                break;
            case R.id.unit_search_btn://单位查询按钮点击事件
                showPopWindow(unit_search_btn);
                break;
        }
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        if (resultCode == 131) {
            initCompanys();//加载公司列表信息
        }
        super.onActivityResult(requestCode, resultCode, data);
    }
}
